<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/3
 * Time: 10:52
 */
namespace app\index\controller;

use think\Loader;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Db;
use think\View;
use think\Controller;
use think\Session;

class Order  extends Controller
{
    public function detail()
    {
        return view('orderdetail');
    }
    //订单列表
    public function lists()
    {
        if (!Session('Login_userId') && !Session('Login_userName')) {

            $this->redirect('/login');die;
            //  $this->redirect('Login/login');die();
        }
        $memberId = Session('Login_userId');
        //服务单
        $list1 = Db::name('service_order so')
            ->join('service_order_service sos', 'so.serviceOrderId=sos.serviceOrderId')
            ->join('service s', 's.serviceId=sos.serviceId')
            ->join('service_order_address ad', 'so.serviceOrderId=ad.serviceOrderId')
            ->join('files f', 'f.filesId=s.iconFileId')
            ->field('so.serviceOrderId,so.memberName,so.paymentStatus,so.orderStatus,so.orderAmount,so.payAmount,so.addDateTime,so.payDateTime,so.serviceType,so.completeDateTime,sos.serviceName,sos.serviceId,f.thumbFile,so.couponId,ad.linkMan,sos.provinceName,sos.cityName,sos.districtName')
            ->where('so.memberId', $memberId)->select();
        //发布单
        $data = Db::name('service_order so')
            ->join('service_order_service sos', 'so.serviceOrderId=sos.serviceOrderId')
            ->join('project p', 'p.projectId=sos.serviceId')
            ->join('service_order_address ad', 'so.serviceOrderId=ad.serviceOrderId')
            ->field('so.serviceOrderId,so.memberName,so.paymentStatus,so.orderStatus,so.orderAmount,so.payAmount,so.addDateTime,so.payDateTime,so.serviceType,so.completeDateTime,sos.serviceName,sos.serviceId,p.projectType,p.tradeLicenseId,so.couponId,ad.linkMan,sos.provinceName,sos.cityName,sos.districtName')
            ->where('serviceType',1) ->where('so.memberId', $memberId)->select();
        foreach ($data as $key => $value) {
            //图标
            if($value['projectType']  == 3){
                $data[$key]['thumbFile'] = Db::name('project_tradelicense')->where('tradeLicenseId', $value['tradeLicenseId'])->join('files', 'files.filesId=project_tradelicense.tradeFileId')->value('thumbFile');
            }else{
                $data[$key]['thumbFile'] = Db::name('project_gallery')->where('projectId', $value['serviceId'])->join('files', 'files.filesId=project_gallery.imgFileId')->order('project_gallery.addDateTime', 'asc')->value('thumbFile');
            }
        }
        //合并三种类型的订单
        $lists = array_merge($list1,$data);
        $infor = Db::name('service_order so')
            ->join('service_order_service sos', 'so.serviceOrderId=sos.serviceOrderId')
            ->field('so.serviceOrderId,so.memberName,so.paymentStatus,so.orderStatus,so.orderAmount,so.addDateTime,so.payDateTime,so.serviceType,so.completeDateTime,sos.serviceName,sos.serviceId,so.memberName,so.payAmount,so.couponId,sos.provinceName,sos.cityName,sos.districtName')->where('so.memberId', $memberId)->where('serviceType',4)->select();
        if(!empty($infor)){
            foreach ($infor as $k => $v) {
                $linkName = $v['memberName'];
                //信息单给个projectType
                $link =array('linkMan'=>$linkName,'projectType'=>7);
                $list[$k] = array_merge($v,$link);
            }
            $list = array_merge($lists,$list);
        }else{
            $list = $lists;
        }
        foreach ($list as $key => $value){
            if($value['couponId']  !=null && $value['couponId']  !=0){
                //优惠券是否过期
                $isCan = isUse($value['couponId']);
                $list[$key]['isCan'] = $isCan;
            }else{
                $list[$key]['isCan'] = 'notUse';
            }
            if(empty($value['projectType'])){
                //服务单给个projectType
                $list[$key]['projectType'] = 8;
            }
        }
        $this->view->assign('list', $list);
        return view('orderlist');
    }
    public function confirm(){
        if (!Session('Login_userId') && !Session('Login_userName')) {
            $this->redirect('/login');die;
        }
        $memberId = Session('Login_userId');
        $memberAddress = Db::name('buyer_address')->where('memberId',$memberId)->select();
        foreach ($memberAddress as $key =>$value)
        {
            $pname = Db::name('area')->where('areaId',$value['province'])->value('areaName');
            $cname = Db::name('area')->where('areaId',$value['city'])->value('areaName');
            $dname = Db::name('area')->where('areaId',$value['district'])->value('areaName');
            $memberAddress[$key]['address'] = $pname.$cname.$dname."  ".$value['address'];
        }
        if(input('serviceId')){
            $data=input();
            $serviceOrderId = $this->serviceAddress($data);
            $order = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->find();
            //价格

            $so = Db::name('service_order_service')->where('serviceOrderId',$serviceOrderId)->find();
            $serviceId = $so["serviceId"];
            $service = Db::name('service')
                ->join('service_category','service.serviceCategoryId=service_category.serviceCategoryId')
                ->where('service.serviceId',$serviceId)->find();
            if(empty($service)){
                //服务表不存在数据则 是发布但或者信息单
                $service = Db::name('project')
                    ->where('projectId',$serviceId)->find();
                if($service['projectType'] == 1){$serviceName = '注册地址';}
                if($service['projectType'] == 2){$serviceName ='众创空间';}
                if($service['projectType'] == 3){$serviceName ='买卖执照';}
                $orderServiceInfo = array(
                    'serviceName' => $service['projectName'],
                    'categoryName'=> $serviceName );
            }else{
                $orderServiceInfo  = array(
                    'serviceName' =>$service['serviceName'],
                    'categoryName'=>$service['categoryName']
                );
            }
            //如果数据库已经选择优惠券，收货地址
            $orderAddress  = Db::name('service_order_address')->where('serviceOrderId',$serviceOrderId)->find();
            if(!empty($orderAddress)){
                $this->view->assign('orderAddress',$orderAddress);
            }
            $this->view->assign('price',$so['sellPrice']);
            $this->view->assign('so',$so);
            $this->view->assign('order',$order);
            $this->view->assign('service',$orderServiceInfo);
            $this->view->assign('soId',$serviceOrderId);
            $price = $so['sellPrice'];
            $canUseCoupon =$this->serviceCoupon($memberId,$price,$serviceId);
        }
        if(input('projectId'))
        {
            //注册地址，营业执照，众创空间 暂时生成即时订单 ，但不入库
            $projectId =input('projectId') ;
            $project = Db::name('project')->where('projectId',$projectId)->find();
            $cateName = Db::name('menu')
                ->join('option','option.menuId=menu.menuId')
                ->where('menu.menuCode','pjt')
                ->where('option.optioncode',$project['projectType'])
                ->value('optionName');
            $service = array(
                'categoryName' => $cateName,
                'serviceName'  => $project['projectName']
            );
            $so['serviceOrderId'] = "FB".$projectId;
            $this->view->assign('so',$so);
            $this->view->assign('projectId',$projectId);
            $this->view->assign('service',$service);
            $this->view->assign('price',$project['price']);
            $price = $project['price'];
            $canUseCoupon =$this->registerAddressCoupon($memberId,$price);

        }
        $this->view->assign('coupon',$canUseCoupon);
        $this->view->assign('member',$memberAddress);
        return view('orderconfirm');
    }
    public function serviceAddress($list)
    {
        if (!Session('Login_userId') && !Session('Login_userName')) {
            $this->redirect('/login');die;
        }


            if (empty($list['price'])){
                $pId = $list['provinceId'];
                $cId = $list['cityId'];
                $dId = $list['districtId'];
                //获取地区名称
                $pName = getAreaName($pId);
                $cName = getAreaName($cId);
                $dName = getAreaName($dId);
                $price = $list['sprice'];

            }else{
                $price = $list['price'];
                $cName = $list['cName'];
                $dName = $list['dName'];
                $pName = $list['pName'];
            }
            $serviceId = $list['serviceId'];
            $serviceOrderId = autoId();//"3043117088458449018";
            $fromMemberId = getProviderId();
            $status = 0;
            // 插入service_order_service
            $sName = Db::name('service')->where('serviceId',$serviceId)->value('serviceName');
            $v = array(
                'serviceOrderServiceId' => autoId(),
                'serviceOrderId'         => $serviceOrderId,
                'serviceId'               => $serviceId,
                'provinceName'            => $pName,
                'cityName'                => $cName,
                'districtName'            => $dName,
                'serviceName'             => $sName,
                'sellPrice'               => $price,
            );
            Db::name('service_order_service')->insert($v);
            // 插入service_order
            $memberId = Session('Login_userId');
            $member = Db::name('member')->where('memberId',$memberId)->find();
            $se = array(
                'serviceOrderId' => $serviceOrderId,
                'memberId' => $memberId,
                'fromMemberId'=> $fromMemberId,
                'toMemberId' =>'',
                'memberName' => $member['memberName'],
                'mobile'=> $member['mobile'],
                'realName' => $member['memberName'],
                'paymentStatus' => 0,
                'orderStatus'=> $status,
                'serviceAmount' =>0,
                'orderAmount'=> 0,
                'payCoupon' => 0,
                'payBalance'=> 0,
                'payIntegral' =>0,
                'payAmount' => 0,
                'payType'=> 0,
                'addDateTime' => aTime(),
                'froms'=> "pc",
                'serviceType' =>0,
                'balanceStatus' => 0,
                'balanceAmount'=> 0,
            );
            $s = DB::name('service_order')->insert($se);
            $providerName = Db::name('member')->where('memberId',getProviderId())->value('memberName');
            $this->sendIn($member['memberName'],$providerName,$member['mobile'],$serviceOrderId);
            if ($s == 1)
            {
                return $serviceOrderId;
            }
            else
            {
                return $serviceOrderId="";
            }

    }
    //下单成功后给用户发短信
    public function sendIn($memberName,$providerName,$phone,$orderNo)
    {
        //支付成功订单下单成功提醒
        $code = array(
            'memberName'=>$memberName,
            'providerName'=>$providerName,
            'orderNo'     => $orderNo,
        );
        $SmsSend = new \app\index\controller\SmsSend();
        $SmsSend -> pay($code,"SMS_79730006",$phone);
    }
    public  function  registerAddressCoupon($memberId,$price){
        //所有可用优惠券
        $canUse =  canUse($memberId);
        $canUseCoupon =array();;
        if(count($canUse)  == 0){
            return  $canUseCoupon;
        }
        //继续过滤（去掉种类不能使用的，或者金额不能用的）
        foreach ($canUse as $k =>$v)
        {
            //去掉种类不能用的
            if($v["categoryName"] == "全品" ){
                //查询金额是否可用
                $couponId =  $v["couponId"];
                //查询优惠券种类
                $couponInfo =  Db::name('coupon')->where('couponId',$couponId)->find();
                if($couponInfo['couponClass'] == 0){
                    //打折
                    $canUseCoupon[] = $v;
                }
                if($couponInfo['couponClass']  == 1){
                    //商品价格
                    //满减或现金抵扣
                    if(($couponInfo['initialAmount'] == 0) || ($couponInfo['initialAmount'] <= $price) ){
                        //是否符合满减规则
                        $canUseCoupon[] = $v;
                    }
                }
            }

        }
        return  $canUseCoupon;
    }
    public  function  serviceCoupon($memberId,$price,$serviceId){
        //所有可用优惠券
        $canUse =  canUse($memberId);
        $canUseCoupon =array();
        if(count($canUse)  == 0){
            return  $canUseCoupon;
        }
        //继续过滤（去掉种类不能使用的，或者金额不能用的）
        foreach ($canUse as $k =>$v)
        {
            $couponInfo =  Db::name('coupon')->where('couponId', $v["couponId"])->find();
            //去掉种类不能用的
            if($v["categoryName"] == "全品" ){
                //查询金额是否可用
                if($couponInfo['couponClass'] == 0){
                    //打折
                    $canUseCoupon[] = $v;
                }
                if($couponInfo['couponClass']  == 1){
                    //商品价格
                    //满减或现金抵扣
                    if(($couponInfo['initialAmount'] == 0) || ($couponInfo['initialAmount'] <= $price) ){
                        //是否符合满减规则
                        $canUseCoupon[] = $v;
                    }
                }
            }else{
                //查询服务所属顶级种类
                $parentCategory =  Db::name('service')
                    ->join('service_category','service.serviceCategoryId=service_category.serviceCategoryId')
                    ->where('serviceId', $serviceId)
                    ->value('parentId');
                $topCategoryName = Db::name('service_category')->where('serviceCategoryId', $parentCategory)->value('categoryName');
                if( $v["categoryName"] == $topCategoryName){
                    //查询金额是否可用
                    if($couponInfo['couponClass'] == 0){
                        //打折
                        $canUseCoupon[] = $v;
                    }
                    if($couponInfo['couponClass']  == 1){
                        //满减或现金抵扣
                        if(($couponInfo['initialAmount'] == 0) || ($couponInfo['initialAmount'] <= $price) ){
                            //是否符合满减规则
                            $canUseCoupon[] = $v;
                        }
                    }
                }
            }

        }
        return  $canUseCoupon;
    }
    //取消订单
    public function cancellation()
    {
        $serviceOrderId = input('id');
        $s = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->update(['orderStatus'=>9]);
//        echo Db::name('service_order')->getLastSql();

        if ($s == 1)
        {
            $res['code'] = 'ok';
            $res['msg'] = '取消订单成功！';
        }else{
            $res['code'] = 'fali';
            $res['msg'] = '取消订单失败！';
        }
        return $res;

    }
    //订单完成
    public  function accomplish()
    {
        if (!Session('Login_userId') && !Session('Login_userName')) {
            $this->redirect('/login');die;
        }
        $serviceOrderId = input('id');
        $service_order = \app\index\model\ServiceOrder::get($serviceOrderId);
        //查询是否结算
        if( $service_order->balanceStatus  == 1){
            $re['code'] = "ok";
            $re['msg'] = "订单结算成功";
            return $re;
        }
        Db::startTrans();
        $re = array();
        try {
            $type = $service_order->serviceType;
            //平台资金
            $pt = Db::name('member_account_log')->where('memberId', 0)->sum('changeAccount');
            //订单来源服务商总余额
            $fromMemberId = $service_order->fromMemberId;
            $fromMemberAmount = Db::name('member_account')->where('memberId', $service_order->fromMemberId)->value('account') ;
            //接单服务商总余额
            $toMemberId = $service_order->toMemberId;
            $toMemberAmount = Db::name('member_account')->where('memberId', $service_order->toMemberId)->value('account') ;
            //推荐人
            $inviterId = Db::name('member')->where('memberId', $service_order->memberId)->value('inviterId');
            if($service_order->couponId ==null){
                $couponId = '0';
            }else{
                $couponId =$service_order->couponId ;
            }
            //推荐人 类型
            $memberType = Db::name('member')->where('memberId', $inviterId)->value('memberType');
            if($memberType == NULL){ $memberType = '1'; }
            //推荐人总钱数
            $inviterAmount = Db::name('member_account')->where('memberId', $inviterId)->value('account') ;
            //推荐比例
            $param = ratio();
            //佣金返现比例
            $commission = commission();
            //来源服务商金额
            if ($type !="信息单") {

                //推荐人奖励，订单来源和推荐人不是一个人，返推荐人
                if ($fromMemberId != $inviterId) {
                    $commissionId = autoId();
                    $commissId = autoId();
                    //插入返现表
                    $commission1   = [
                        'serviceOrderCommissionId' => $commissionId,
                        'providerId' => $fromMemberId,
                        'serviceOrderId' => $serviceOrderId,
                        'serviceOrderAmount' =>  $service_order->orderAmount,
                        'level'=>0,
                        'couponId'=>$couponId,
                        'memberId' => $inviterId,
                        'parentMemberType' => $memberType,
                        'returnRatio' => $param,
                        'returnType' => 0,
                        'status' => 1,
                        'remark' => "消费推荐人奖励",
                        'addDateTime' => aTime()
                    ];
                    Db::name('service_order_commission')->insert($commission1);
                    //资金变动
                    $account = array(
                        'account'=>$inviterAmount +  $service_order->payAmount * $param,
                        'changeTime'=>aTime()
                    );
                    Db::name('member_account')->where(array('memberId'=>$inviterId))->update($account);
                    //资金变动日志
                    $log1 = [
                        'memberAccountLogId' => autoId(),
                        'memberId' => $inviterId,
                        'balanceAccount' => $inviterAmount + $service_order->payAmount * $param,
                        'changeAccount' => $service_order->payAmount * $param,
                        'businessId' => $commissionId,
                        'businessType' => 5,
                        'isAuto' => 0,
                        'addDateTime' => aTime(),
                        'tradeMemberId'=>$service_order->memberId,
                        'operator' => $service_order->memberName
                    ];
                    $tuijian=$service_order->payAmount * $param;
                    Db::name('member_account_log')->insert($log1);
                }else{
                    $tuijian=0;
                }
                //订单来源和接单人不是一个人
                if ($fromMemberId != $toMemberId) {
                    //返订单来源 返佣
                    $commissionId2 = autoId();
                    $commission2 = [
                        'serviceOrderCommissionId' => $commissionId2,
                        'providerId' => $fromMemberId,
                        'serviceOrderId' => $serviceOrderId,
                        'serviceOrderAmount' => $service_order->orderAmount,
                        'level'=>0,
                        'couponId'=>$couponId,
                        'memberId' => $fromMemberId,
                        'parentMemberType' => 1,
                        'returnRatio' => $commission,
                        'returnType' => 0,
                        'status' => 1,
                        'remark' => "消费服务商返佣",
                        'addDateTime' => aTime()
                    ];
                    Db::name('service_order_commission')->insert($commission2);

                    //资金变动
                    $fromMemberAccount = array(
                        'account'=> $fromMemberAmount + ($service_order->payAmount * $commission),
                        'changeTime'=>aTime()
                    );
                    Db::name('member_account')->where(array('memberId'=>$fromMemberId))->update($fromMemberAccount);
                    $log2 = [
                        'memberAccountLogId' => autoId(),
                        'memberId' => $fromMemberId,
                        'balanceAccount' => $fromMemberAmount + ($service_order->payAmount * $commission),
                        'changeAccount' => $service_order->payAmount * $commission,
                        'businessId' => $commissionId2,
                        'businessType' => 6,
                        'isAuto' => 0,
                        'addDateTime' => aTime(),
                        'tradeMemberId'=>0,
                        'operator' => $service_order->memberName
                    ];
                    Db::name('member_account_log')->insert($log2);
                    $youjin=$service_order->payAmount * $commission;
                }
                else {
                    $youjin=0;
                }
            }
            //结算金额
            $jieAmount =  $service_order->payAmount -$youjin-$tuijian ;
            //订单结算  操作接单人资金
            //资金变动
            $toMemberAccount = array(
                'account'=> $toMemberAmount + $jieAmount,
                'changeTime'=>aTime()
            );
            Db::name('member_account')->where(array('memberId'=>$service_order->toMemberId))->update($toMemberAccount);
            $log4 = [
                'memberAccountLogId' => autoId(),
                'memberId' => $service_order->toMemberId,
                'balanceAccount' => $toMemberAmount + $jieAmount,
                'changeAccount' => $jieAmount,
                'businessId' => $serviceOrderId,
                'businessType' => 7,
                'isAuto' => 0,
                'addDateTime' => aTime(),
                'tradeMemberId'=>0,
                'operator' => $service_order->memberName
            ];
            Db::name('member_account_log')->insert($log4);
//            echo Db::name('member_account_log')->getLastSql();die;
            Db::commit();
            $s = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->update(['orderStatus'=>7,'balanceStatus'=>1,'balanceAmount'=>$jieAmount]);
            if ($s==1)
            {
                $re['code'] = "ok";
                $re['msg'] = "订单结算成功";
            }else{
                Db::rollback();
                $re['code'] = "fali";
                $re['msg'] = "订单结算失败";
            }

        } catch (\Exception $e) {
            Db::rollback();
            $re['code'] = "fail";
            $re['msg'] = "订单结算失败";
        }
        return $re;

    }
    //确定订单  提交的内容
    public function beforeSendPay()
    {
        if (!Session('Login_userId') && !Session('Login_userName')) {
            $this->redirect('/login');die;
        }
        $address = $_POST['ad'];
        if (!isset($address))
        {
            $re['code'] = "fail";
            $re['msg'] = "未设置收货地址，请先设置收货地址";
            return $re;

        }
        $mobile = $_POST['tp'];
        $serviceOrderId = $_POST['so'];
        $type =  substr($serviceOrderId,0,2);
        $memberId = Session('Login_userId');
        $member = Db::name('member')->where('memberId',$memberId)->find();
        if($type=="FB")
        {
            //发布单下订单
            $projectId =  str_replace("FB","",$serviceOrderId);
            $project = Db::name('project')->where('projectId',$projectId)->find();
            $serviceOrderId  = autoId();
            //新增servive_order_service
            $pName = Db::name('area')->where('areaId',$project['provinceId'])->value('areaName');
            $cName = Db::name('area')->where('areaId',$project['cityId'])->value('areaName');
            $dName = Db::name('area')->where('areaId',$project['districtId'])->value('areaName');
            //获取发布单所属服务商
            $toMemberId = Db::name('project')->where('projectId',$projectId)->value('memberId');
            $v = array(
                'serviceOrderServiceId' => autoId(),
                'serviceOrderId'         => $serviceOrderId,
                'serviceId'               => $projectId,
                'provinceName'            => $pName,
                'cityName'                => $cName,
                'districtName'            => $dName,
                'serviceName'             => $project['projectName'],
                'sellPrice'               => $project['price'],
            );
            Db::name('service_order_service')->insert($v);
            $se = array(
                'serviceOrderId' => $serviceOrderId,
                'memberId' => $memberId,
                'fromMemberId'=> getProviderId(),
                'toMemberId' =>$toMemberId,
                'memberName' => $member['memberName'],
                'mobile'=> $member['mobile'],
                'realName' => $member['memberName'],
                'paymentStatus' => 0,
                'orderStatus'=> 0,
                'serviceAmount' =>0,
                'orderAmount'=> 0,
                'payCoupon' => 0,
                'payBalance'=> 0,
                'payIntegral' =>0,
                'payAmount' => 0,
                'payType'=> 0,
                'addDateTime' => aTime(),
                'froms'=> "pc",
                'serviceType' =>1,
                'balanceStatus' => 0,
                'balanceAmount'=> 0,
            );
            $order = DB::name('service_order')->insert($se);
            if ($order==1)
            {
                $providerName = Db::name('member')->where('memberId',getProviderId())->value('memberName');
                $this->sendIn($member['memberName'],$providerName,$member['mobile'],$serviceOrderId);
            }
            $soId = "FB".$serviceOrderId;
        }else{
            $soId = $serviceOrderId;
        }
        //查询是否已下单
        $orderStatus =  Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->value('orderStatus');
        //用户地址  电话  和联系人 都是在用户信息中查询
        $couponId = $_POST['couponId'];
        if(!empty($_POST['linkman']))
        {
            $linkMan = $_POST['linkman'];
        }
        else
        {
            $linkMan = $member['mobile'] ;
        }
        $price = $_POST['price'];
        //判断是否使用优惠券
        if ($_POST['couponsprice']){
            $couponsprice = $_POST['couponsprice'];
        }else{
            $couponsprice = 0;
        }
        $shiprice = $_POST['shiprice'];
        if($_POST['couponId'])
        {
            //更新优惠券
            Db::name('buyer_coupon')->where(array('buyerCouponId'=>$_POST['couponId']))->update(array('status'=>1));
        }

        //送货地址
        if($orderStatus ==1 ){
            $service_order_address =  Db::name('service_order_address')->where('serviceOrderId',$serviceOrderId)->find();
            if($service_order_address){
                $service_address = array(
                    'address'       => $address,
                    'tel'           => $mobile,
                    'linkMan'       => $linkMan,
                );
                Db::name('service_order_address')->where('serviceOrderId',$serviceOrderId)->update($service_address);
            }else{
                $service_address = array(
                    'serviceOrderId' => $serviceOrderId,
                    'address'       => $address,
                    'tel'           => $mobile,
                    'linkMan'       => $linkMan,
                );
                Db::name('service_order_address')->insert($service_address);
            }

        }else{
            $service_address = array(
                'serviceOrderId' => $serviceOrderId,
                'address'       => $address,
                'tel'           => $mobile,
                'linkMan'       => $linkMan,
            );
            Db::name('service_order_address')->insert($service_address);
        }
        //更新订单资金相关的信息
        $se = array(
            'orderStatus'=> 1,
            'serviceAmount' => $price,
            'orderAmount'=> $price,
            'couponId'   => $couponId,
            'payCoupon' => $couponsprice,
            'payAmount' => $shiprice,
            'addDateTime' => aTime(),
        );
        Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->update($se);
        $re['soid'] = $soId;
        $re['code'] = "ok";
        $re['msg'] = "下单成功";
        return $re;

    }
    public  function  sendPay(){
        if(isset($_GET['serviceOrderId'])){
            if (!Session('Login_userId') && !Session('Login_userName')) {
                $this->redirect('/login');die;
            }
            $serviceOrderId = $_GET['serviceOrderId'] ;
            //订单类型为发布单时
            $t =  substr($serviceOrderId,0,2);
            if($t == "FB")
            {
                $serviceOrderId =  str_replace("FB","",$serviceOrderId);
            }
            $type = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->value('serviceType');
            if ($type==1)
            {
                //订单类型为发布单时
                $order = Db::name('service_order_service sos ')
                    ->join('project p','sos.serviceId=p.projectId')
                    ->join('service_order_address soa','sos.serviceOrderId=soa.serviceOrderId')
                    ->join('service_order so','sos.serviceOrderId=so.serviceOrderId')
                    ->where('sos.serviceOrderId',$serviceOrderId)->find();
            }
            else
            {
                //其他类型订单
                $order = Db::name('service_order_service sos ')
                    ->join('service s','sos.serviceId=s.serviceId')
                    ->join('service_order_address soa','sos.serviceOrderId=soa.serviceOrderId')
                    ->join('service_order so','sos.serviceOrderId=so.serviceOrderId')
                    ->where('sos.serviceOrderId',$serviceOrderId)->find();
            }
            $this->view->assign('order',$order);

        }else if(isset($_GET['NoOrderNumId'])){
            $res =  Db::name('member sos')
                ->join('noordernum s','sos.memberId=s.memberId')
                ->where('NoOrderNumId',$_GET['NoOrderNumId'])
                ->find();
            //服务商区域
            $district =   Db::name('area')->where('areaId',$res['areaId'])->field('areaName,parentId')->find();
            $city =   Db::name('area')->where('areaId',$district['parentId'])->field('areaName,parentId')->find();
            $province =   Db::name('area')->where('areaId',$city['parentId'])->field('areaName,parentId')->find();
            $order['address']  =  $province['areaName'].$city['areaName'].$district['areaName'];
            $order['tel']  = $res['mobile'];
            $order['linkMan']  = $res['memberName'];
            $order['serviceName']  = '成为服务商';
            $order['serviceOrderId']  =  $_GET['NoOrderNumId'];
            $order['memberId'] = $res['memberId'];
            $order['payAmount']  =$res['amount'];
            $order['type']  = 'register';
            $this->view->assign('order',$order);
        }elseif($_GET['information']){
            //查看联系方式付款
            $serviceOrderId = autoId();
            $memberId = Session('Login_userId');
            $member = Db::name('member')->where('memberId',$memberId)->find();
            $project = Db::name('project')->where('projectId',$_GET['information'])->find();
            $pName = Db::name('area')->where('areaId',$project['provinceId'])->value('areaName');
            $cName = Db::name('area')->where('areaId',$project['cityId'])->value('areaName');
            $dName = Db::name('area')->where('areaId',$project['districtId'])->value('areaName');
            $v = array(
                'serviceOrderServiceId' => autoId(),
                'serviceOrderId'         => $serviceOrderId,
                'serviceId'               => $_GET['information'],
                'provinceName'            => $pName,
                'cityName'                => $cName,
                'districtName'            => $dName,
                'serviceName'             => "查看".$project['projectName']."项目联系方式",
                'sellPrice'               => 5,
            );
            DB::name('service_order_service')->insert($v);
            $se = array(
                'serviceOrderId' => $serviceOrderId,
                'memberId' => $memberId,
                'fromMemberId'=> getProviderId(),
                'toMemberId' =>0,
                'memberName' => $member['memberName'],
                'mobile'=> $member['mobile'],
                'realName' => $member['memberName'],
                'paymentStatus' => 0,
                'orderStatus'=> 0,
                'serviceAmount' =>0,
                'orderAmount'=> 5,
                'payCoupon' => 0,
                'payBalance'=> 0,
                'payIntegral' =>0,
                'payAmount' => 5,
                'payType'=> 0,
                'addDateTime' => date('Y-m-d H:i:s'),
                'froms'=> "pc",
                'serviceType' =>4,
                'balanceStatus' => 1,
                'balanceAmount'=> 5,
            );

            $service = DB::name('service_order')->insert($se);
            if ($service==1){
                $order['serviceOrderId'] = $serviceOrderId;
                $order['projectId'] = $_GET['information'];
                $order['payAmount'] = 5;
                $order['memberId'] = $memberId;
                $this->view->assign('order',$order);
            }

        }
        else{
            echo "订单号错误";
        }
        //获取支付密码
        if(Session::get('Login_userId')){
            $tradePwd =   Db::name('memberAccount')->where(array('memberId' => Session::get('Login_userId')))->value('tradePwd');
            if($tradePwd =='' ||$tradePwd ==null ){  $hasPWD ='no';}else{
                $hasPWD ='yes';
            }
        }else{
            $hasPWD ='no';
        }
        $this->view->assign('hasPWD',$hasPWD);
        $account= Db::name('member_account')->where(array('memberId'=>Session::get('Login_userId')))->value('account');
        $this->view->assign('account',$account);
        return view('selectpay');
    }
    //支付宝支付跳转
    public function orderalert2()
    {
        //查询订单是否为合作入驻服务商订单
        if (substr(input('orderId'),0,2 ) == 'JM') {
            $where = [
                'NoOrderNumId' => input('orderId'),
                'memberId'     => input('memberId'),

            ];
            $v = Db::name('noordernum')
                ->where($where)->find();

            if (!empty($v))
            {
                //查询是否支付
                if($v['payStatus'] != 0){
                    $res['code'] = 'fail';
                    $res['msg'] ='订单已支付';
                    $this->view->assign('text',$res);
                    return view('orderalert2');
                }
                $orderInfo=array(
                    //订单加密
                    'out_trade_no' =>input('orderId'),
                    'total_amount' =>input('price'),
                    'subject' =>'成为服务商',
                );
            }else{
                $res['code'] = 'fail';
                $res['msg'] ='订单不存在';
                $this->view->assign('text',$res);
                return view('orderalert2');
            }

        } else{
            //数据库查询订单信息
            $serviceOrderId = input('orderId');
            $service = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->find();
            if(!empty($service)){
                //查询是否支付
                if($service['paymentStatus'] != 0){
                    $res['code'] = 'fail';
                    $res['msg'] ='订单已支付';
                    $this->view->assign('text',$res);
                    return view('orderalert2');
                }
                if($service['serviceType'] == 4){
                    $orderInfo=array(
                        //订单加密
                        'out_trade_no' =>$serviceOrderId,
                        'total_amount' =>5,
                        'subject' =>'查看信息订单',
                    );
                }else{
                    $order = Db::name('service_order so')
                        ->join('service_order_service sos','so.serviceOrderId=sos.serviceOrderId')
                        ->where('so.serviceOrderId',$serviceOrderId)
                        ->find();
                    $orderInfo=array(
                        //订单加密
                        'out_trade_no' =>$serviceOrderId,
                        'total_amount' =>input('price'),
                        'subject' => $order['serviceName'],
                    );
                }
            }else{
                $res['code'] = 'fail';
                $res['msg'] ='订单不存在';
                $this->view->assign('text',$res);
                return view('orderalert2');
            }

        }
        $config = array (
            //应用ID,您的APPID。
            'app_id' => Db::name('param')->where(array('paramCode'=>'ALIPAY_APPID'))->value('paramValue'),

            //商户私钥
            'merchant_private_key' => Db::name('param')->where(array('paramCode'=>'ALIPAY_KEY'))->value('paramValue'),

            //异步通知地址
            'notify_url' => Db::name('param')->where(array('paramCode'=>'ALIPAY_NOTIFY'))->value('paramValue'),

            //同步跳转
            'return_url' => "http://".$_SERVER['HTTP_HOST']."/payment3.html",

            //编码格式
            'charset' => "UTF-8",

            //签名方式
            'sign_type'=>"RSA2",

            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",

            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => Db::name('param')->where(array('paramCode'=>'ALIPAY_NOTIFY_OPEN'))->value('paramValue'),
        );
//        var_dump(EXTEND_PATH);die;
//        Loader::import('wappay\wappay\Pay', EXTEND_PATH);
        $pay =new  \wappay\Pay();
        $pay ->pay($config,$orderInfo);
    }
//    //支付宝支付跳转
//    public function orderalert2()
//    {
//        //查询订单是否为合作入驻服务商订单
////        if (substr(input('orderId'),0,2 ) == 'JM') {
////            $where = [
////                'NoOrderNumId' => input('orderId'),
////                'memberId'     => input('memberId'),
////
////            ];
////            $v = Db::name('noordernum')
////                ->where($where)->find();
////
////            if (!empty($v))
////            {
////                //查询是否支付
////                if($v['payStatus'] != 0){
////                    $res['code'] = 'fail';
////                    $res['msg'] ='订单已支付';
////                    $this->view->assign('text',$res);
////                    return view('orderalert2');
////                }
////                $orderInfo=array(
////                    //订单加密
////                    'out_trade_no' =>input('orderId'),
////                    'total_amount' =>input('price'),
////                    'subject' =>'成为服务商',
////                );
////            }else{
////                $res['code'] = 'fail';
////                $res['msg'] ='订单不存在';
////                $this->view->assign('text',$res);
////                return view('orderalert2');
////            }
////
////        } else{
////            //数据库查询订单信息
////            $serviceOrderId = input('orderId');
////            $service = Db::name('service_order')->where('serviceOrderId',$serviceOrderId)->find();
////            if(!empty($service)){
////                //查询是否支付
////                if($service['paymentStatus'] != 0){
////                    $res['code'] = 'fail';
////                    $res['msg'] ='订单已支付';
////                    $this->view->assign('text',$res);
////                    return view('orderalert2');
////                }
////                if($service['serviceType'] == 4){
////                    $orderInfo=array(
////                        //订单加密
////                        'out_trade_no' =>$serviceOrderId,
////                        'total_amount' =>5,
////                        'subject' =>'查看信息订单',
////                    );
////                }else{
////                    $order = Db::name('service_order so')
////                        ->join('service_order_service sos','so.serviceOrderId=sos.serviceOrderId')
////                        ->where('so.serviceOrderId',$serviceOrderId)
////                        ->find();
////                    $orderInfo=array(
////                        //订单加密
////                        'out_trade_no' =>$serviceOrderId,
////                        'total_amount' =>input('price'),
////                        'subject' => $order['serviceName'],
////                    );
////                }
////            }else{
////                $res['code'] = 'fail';
////                $res['msg'] ='订单不存在';
////                $this->view->assign('text',$res);
////                return view('orderalert2');
////            }
////
////        }
//        $config =array(
//        'partner'           =>'2088111111116894',
//        'seller_id'         =>'2088111111116894',//和上面一样
//        'key'       =>'j60fqq5a*********vsi1w4iz9t',
//        'notify_url'        =>'http://'.$_SERVER['HTTP_HOST'].'/index/alipay/alipay_wap_notify',
//        'return_url'        =>'http://'.$_SERVER['HTTP_HOST'].'/index/alipay/alipay_wap_return',
//        'sign_type'         =>strtoupper('MD5'),
//        'input_charset'         =>strtolower('utf-8'),
//        'cacert'            =>getcwd().'\\cacert.pem',//需要放在根目录
//        'transport'         =>'http',
//        'payment_type'      =>'1',
//        'service'           =>'alipay.wap.create.direct.pay.by.user'
//        );
//        return $config;
//    }
//    //表单提交支付
//    public function alipay_wap_do()
//    {
//        $pay =new  \Alipay\AlipayTradeService;
//        require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'service/AlipayTradeService.php';
//        require_once dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'buildermodel/AlipayTradeWapPayContentBuilder.php';
//        require dirname ( __FILE__ ).DIRECTORY_SEPARATOR.'./../config.php';
//        if (!empty($_POST['WIDout_trade_no'])&& trim($_POST['WIDout_trade_no'])!=""){
//            //商户订单号，商户网站订单系统中唯一订单号，必填
//            $out_trade_no = $_POST['WIDout_trade_no'];
//
//            //订单名称，必填
//            $subject = $_POST['WIDsubject'];
//
//            //付款金额，必填
//            $total_amount = $_POST['WIDtotal_amount'];
//
//            //商品描述，可空
//            $body = $_POST['WIDbody'];
//
//            //超时时间
//            $timeout_express="1m";
//
//            $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
//            $payRequestBuilder->setBody($body);
//            $payRequestBuilder->setSubject($subject);
//            $payRequestBuilder->setOutTradeNo($out_trade_no);
//            $payRequestBuilder->setTotalAmount($total_amount);
//            $payRequestBuilder->setTimeExpress($timeout_express);
//
//            $payResponse = new AlipayTradeService($config);
//            $result=$payResponse->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);
//
//            return ;
//        }
//    }
//
//    public function alipay_wap_notify()
//    {
//        $alipay_config = Config::get('alipay_wap_config');
//        //计算得出通知验证结果
//        $alipayNotify = new \Alipay_wap\AlipayNotify($alipay_config);
//        $verify_result = $alipayNotify->verifyNotify();
//
//        if ($verify_result) {//验证成功
//            /////////////////////////////////////////////////////////
//            ////////////////////////////////////////////////////////////////////////////
//            //请在这里加上商户的业务逻辑程序代
//
//
//            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
//
//            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
//
//            //商户订单号
//
//            $out_trade_no = $_POST['out_trade_no'];
//
//            //支付宝交易号
//
//            $trade_no = $_POST['trade_no'];
//
//            //交易状态
//            $trade_status = $_POST['trade_status'];
//
//
//            if ($_POST['trade_status'] == 'TRADE_FINISHED') {
//                //判断该笔订单是否在商户网站中已经做过处理
//                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
//                //如果有做过处理，不执行商户的业务程序
//
//                //注意：
//                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
//
//                //调试用，写文本函数记录程序运行情况是否正常
//                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
//            } else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
//                //判断该笔订单是否在商户网站中已经做过处理
//                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
//                //如果有做过处理，不执行商户的业务程序
//
//                //注意：
//                //付款完成后，支付宝系统发送该交易状态通知
//
//                //调试用，写文本函数记录程序运行情况是否正常
//                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
//            }
//
//            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//
//            echo "success";        //请不要修改或删除
//
//            ////////////////////////////////////////////////////////////
//            /////////////////////////////////////////////////////////////////////////
//        } else {
//            //验证失败
//            echo "fail";
//
//            //调试用，写文本函数记录程序运行情况是否正常
//            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
//        }
//    }
//
//    public function alipay_wap_return()
//    {
//        $alipay_config = Config::get('alipay_wap_config');
//        //计算得出通知验证结果
//        $alipayNotify = new \Alipay_wap\AlipayNotify($alipay_config);
//        $verify_result = $alipayNotify->verifyReturn();
//        if ($verify_result) {//验证成功
//            //
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//            //**************************请在这里加上商户的业务逻辑程序代码***********************
//
//            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
//            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
//
//            //商户订单号
//
//            $out_trade_no = $_GET['out_trade_no'];
//
//            //支付宝交易号
//
//            $trade_no = $_GET['trade_no'];
//
//            //交易状态
//            $trade_status = $_GET['trade_status'];
//
//
//            if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
//                //判断该笔订单是否在商户网站中已经做过处理
//                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//                //如果有做过处理，不执行商户的业务程序
//            } else {
//                echo "trade_status=" . $_GET['trade_status'];
//            }
//
//            /*echo "验证成功<br />";*/
//            //p($_GET);die;
//
//            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//
//            /**验证成功，请加入自己逻辑**/
//        }
//        /////////////////////////////////////////////////////////////////
//        ////////////////////////////////////////////////////////////////////
//        else {
//            //验证失败
//            //如要调试，请看alipay_notify.php页面的verifyReturn函数
//            echo "验证失败";
//        }
//    }
}